package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
)

type Result3 struct {
	Data []struct {
		Author            string      `json:"author"`
		Cip               interface{} `json:"cip"`
		Clc               string      `json:"clc"`
		Code              string      `json:"code"`
		Content           interface{} `json:"content"`
		CopiesCount       interface{} `json:"copiesCount"`
		Edition           interface{} `json:"edition"`
		Editor            interface{} `json:"editor"`
		EnglishName       string      `json:"englishName"`
		Folio             interface{} `json:"folio"`
		Illustrator       interface{} `json:"illustrator"`
		Image             interface{} `json:"image"`
		Introduction      string      `json:"introduction"`
		Isbn              string      `json:"isbn"`
		Name              string      `json:"name"`
		PageCount         interface{} `json:"pageCount"`
		Price             interface{} `json:"price"`
		Print             interface{} `json:"print"`
		Publisher         string      `json:"publisher"`
		PublishingAddress string      `json:"publishingAddress"`
		PublishingTime    string      `json:"publishingTime"`
		Score             interface{} `json:"score"`
		SeriesName        interface{} `json:"seriesName"`
		Size              interface{} `json:"size"`
		SplitIsbn         interface{} `json:"splitIsbn"`
		Title             string      `json:"title"`
		Translate         interface{} `json:"translate"`
		Weight            interface{} `json:"weight"`
	} `json:"data"`
	Error  interface{} `json:"error"`
	Status int         `json:"status"`
}

func QueryIsbn3(isbn string) ([]*BookItem, error) {
	if len(isbn) == 0 {
		return nil, errors.New("isbn 为空")
	}
	var isbnUrl = "http://49.234.70.238:9001/book/worm/isbn?isbn="
	req, err := http.NewRequest("GET", isbnUrl+isbn, nil)
	if err != nil {
		return nil, err
	}
	q := req.URL.Query()
	q.Add("isbn", isbn)
	req.URL.RawQuery = q.Encode()
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	resJsonStr, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	fmt.Printf("isbn:%v str:%v\n", isbn, string(resJsonStr))
	var resObj Result3
	err = json.Unmarshal(resJsonStr, &resObj)
	if err != nil {
		fmt.Println(string(resJsonStr))
		return nil, err
	}
	if resObj.Status != 200 {
		return nil, errors.New("not 200")
	}
	var books []*BookItem
	for _, datum := range resObj.Data {
		books = append(books, &BookItem{
			Isbn:        isbn,
			Title:       datum.Name,
			AuthorName:  datum.Author,
			Logo:        "",
			Publisher:   datum.Publisher,
			Published:   datum.PublishingTime,
			Page:        "",
			Price:       "",
			Designed:    "",
			Description: "",
			Count:       2,
		})
	}
	return books, nil
}
